import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:frontend/models/address.dart';
import 'package:frontend/models/global.dart';
import 'package:frontend/models/itemInfo.dart';

import '../reqs/requests.dart';

class OrderPage extends StatefulWidget {
  const OrderPage({super.key, required this.itemId});

  final int itemId;

  @override
  State<StatefulWidget> createState() {
    return OrderPageState();
  }
}

class OrderPageState extends State<OrderPage> {
  Address? selectedAddress;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("确认订单"),
      ),
      body: FutureBuilder(
          future: queryItemInfo(widget.itemId),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                return const Icon(Icons.error);
              } else {
                return Container(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    children: [
                      SizedBox(
                        height: 500.0,
                        width: 550.0,
                        child:
                            ClipOval(child: Image.memory(snapshot.data!.img)),
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.max,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Column(
                            children: [
                              Text(
                                snapshot.data!.name,
                                style: TextStyle(
                                  fontSize: 42.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              Text(
                                '￥ ${snapshot.data!.price}',
                                style: TextStyle(
                                    fontSize: 28.0,
                                    fontWeight: FontWeight.w200,
                                    color: Colors.grey),
                              ),
                              Text(
                                snapshot.data!.description,
                                style: TextStyle(
                                  fontSize: 20.0,
                                  fontWeight: FontWeight.normal,
                                ),
                              )
                            ],
                          ),
                        ],
                      ),
                      _buildDivider(),
                      Text(
                        "收货地址：${selectedAddress?.address ?? "未选择"}",
                        style: TextStyle(
                          fontSize: 20.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      ElevatedButton(
                          onPressed: () async {
                            bool? res =
                                await _showModalBottomSheet(snapshot.data!);
                            if (res != null) {
                              if (!Global.profile.isLogin) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  const SnackBar(
                                    content: Text('请先登录'),
                                  ),
                                );
                              } else {
                                submitOrder(
                                    Global.profile.user!.id,
                                    snapshot.data!.id,
                                    selectedAddress!.address_id);
                                ScaffoldMessenger.of(context).showSnackBar(
                                  const SnackBar(
                                    content: Text('订单已提交'),
                                  ),
                                );
                              }
                            }
                          },
                          child: const Text("确认订单")),
                      _buildDivider(),
                    ],
                  ),
                );
              }
            } else {
              // 请求未结束，显示loading
              return const CircularProgressIndicator();
            }
          }),
    );
  }

  _buildDivider() {
    return Divider(
      color: Theme.of(context).textTheme.caption!.color,
    );
  }

  Future<bool?> _showModalBottomSheet(ItemInfo info) {
    return showModalBottomSheet<bool>(
      context: context,
      builder: (BuildContext context) {
        return ListView(
          children: [
            Text("确认提交订单？",
                style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.w600,
                    fontSize: 32)),
            Text(info.name,
                style: TextStyle(
                    color: Colors.grey,
                    fontWeight: FontWeight.w300,
                    fontSize: 16)),
            Text("￥${info.price}",
                style: TextStyle(
                    color: Colors.lightBlueAccent,
                    fontWeight: FontWeight.w200,
                    fontSize: 16)),
            FutureBuilder<List<Address>>(
                future: fetchAddresses(Global.profile.user!.id),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError) {
                      return Text(snapshot.error.toString());
                    }
                    return ListTile(
                      title: Text(selectedAddress != null
                          ? selectedAddress!.address
                          : '选择地址'),
                      trailing: PopupMenuButton<Address>(
                        padding: EdgeInsets.zero,
                        onSelected: (value) {
                          setState(() {
                            selectedAddress = value;
                          });
                          Navigator.of(context).pop();
                        },
                        itemBuilder: (context) => <PopupMenuItem<Address>>[
                          for (var address in snapshot.data!)
                            PopupMenuItem<Address>(
                              value: address,
                              child: Text(
                                "${address.tag} ${address.contact} ${address.address} ${address.phone_number}",
                              ),
                            ),
                        ],
                      ),
                    );
                  } else {
                    return ListTile(
                      title: Text('选择地址'),
                    );
                  }
                }),
            ElevatedButton(
                onPressed: () {
                  if (selectedAddress == null) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('请选择收货地址'),
                      ),
                    );
                  } else {
                    Navigator.of(context).pop(true);
                  }
                },
                child: Text("提交订单"))
          ],
        );
      },
    );
  }
}

class AddressSelect extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    throw UnimplementedError();
  }
}

class AddressSelectState extends State<AddressSelect> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}
